<template>
  <div>
    <el-upload action="#" list-type="picture-card" :file-list="filelist" :class="{disablie:filelist.length > 0}" :on-preview="onPreview" :on-remove="onRemove" :on-change="onChange" :http-request="upload" :before-upload="beforeUpload">
      <i class="el-icon-plus" />
    </el-upload>
    <el-dialog :visible="isShowDialog" title="预览头像" @close="isShowDialog=false">
      <el-row type="flex" justify="center">
        <img :src="PreviewUrl" alt="">
      </el-row>
    </el-dialog>
    <el-progress v-if="isshowprogress" :text-inside="true" :stroke-width="20" :percentage="percentage" status="success" style="width:146px" />
  </div>
</template>

<script>
import COS from 'cos-js-sdk-v5'
var cos = new COS({
  SecretId: 'AKIDFRQ9cuymOltmPmshFXeV6SYOyKSM0vd5',
  SecretKey: 'D9pDMFrBE0YpJacPwEG4cvytZ0B6mDPL'
})
export default {
  data() {
    return {
      filelist: [],
      PreviewUrl: '',
      isShowDialog: false,
      percentage: 0,
      isshowprogress: false
    }
  },
  methods: {
    onPreview(file) {
      this.PreviewUrl = file.url
      this.isShowDialog = true
    },
    onRemove(file, newfilelist) {
      this.filelist = newfilelist
    },
    onChange(file, newfilelist) {
      console.log(newfilelist)
      this.filelist = newfilelist
    },
    beforeUpload(file) {
      if (file.type.indexOf('image/') === -1) {
        this.$message.error('目前只能以图片格式上传!')
        return false
      }
      const maxsize = 2 * 1024 * 1024
      if (file.size > maxsize) {
        this.$message.warning('图片大小不能超过 2M')
        return false
      }
    },
    upload(obj) {
      this.isshowprogress = true
      cos.putObject({
        Bucket: 'liuwawa-1259000455', /* 必须 */
        Region: 'ap-guangzhou', /* 存储桶所在地域，必须字段 */
        Key: obj.file.name, /* 必须 */
        StorageClass: 'STANDARD',
        Body: obj.file, // 上传文件对象
        onProgress: (progressData) => {
          this.percentage = Math.round(progressData.percent * 100)
        }
      }, (err, data) => {
        console.log(err || data)
        setTimeout(() => {
          this.isshowprogress = false
        }, 800)
        this.filelist[0].url = 'http://' + data.Location
        this.filelist[0].status = 'success'
      })
    }

  }
}
</script>

<style lang="scss" scoped>
.disablie{
    ::v-deep .el-upload--picture-card{
    display: none;
}
}
img {
  object-fit: cover
}
</style>
